<template>
  <div class="student">
    <el-card>
      <!-- 搜索 -->
      <div class="search">
        <el-form :inline="true">
          <el-form-item label="用户名：">
            <el-input v-model="params.userName" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleQuery">查询</el-button>
            <el-button :disabled="loading" @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <el-table :data="tableData" style="width: 100%" :loading="loading" stripe>
        <el-table-column prop="id" label="id" width="70" />
        <el-table-column prop="userName" label="用户名" width="130" />
        <el-table-column prop="realName" label="真实姓名" width="130" />
        <el-table-column prop="userLevel" label="年级" width="120">
          <template #default="{ row }">{{ levelMap[row.userLevel] || "-" }}</template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="70">
          <template #default="{ row }">
            {{ row.sex === 1 ? "男" : row.sex === 2 ? "女" : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="warning" size="small" @click="handleToggleStatus(row)">
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" @click="handleLog(row)">日志</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="params.pageIndex"
          v-model:page-size="params.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import UserAPI, { type UserParams, type UserType } from "@/api/system/user.api";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";

// 年级映射：1-6 小学，7-9 初中，10-12 高中
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const tableData = ref<UserType[]>([]);
const total = ref(0);
const loading = ref(false);

// 接口参数
const params = ref<UserParams>({
  userName: "",
  role: 1,
  pageIndex: 1,
  pageSize: 10,
});

// 获取列表
function getList() {
  loading.value = true;
  UserAPI.getUserPage(params.value)
    .then((data: any) => {
      tableData.value = data.list || [];
      total.value = data.total || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleQuery() {
  params.value.pageIndex = 1;
  getList();
}
function handleReset() {
  params.value.userName = "";
  params.value.pageIndex = 1;
  getList();
}
function handleSizeChange(size: number) {
  params.value.pageSize = size;
  params.value.pageIndex = 1;
  getList();
}
function handleCurrentChange(page: number) {
  params.value.pageIndex = page;
  getList();
}

// 操作按钮占位
function handleToggleStatus(row: UserType) {
  const newStatus = row.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? "启用" : "禁用";

  UserAPI.changeStatus(row.id)
    .then(() => {
      row.status = newStatus;
      ElMessage.success(`${actionText}成功`);
    })
    .catch(() => {
      ElMessage.error(`${actionText}失败`);
    });
}
const router = useRouter();

function handleEdit(row: UserType) {
  router.push({ name: "StudentEditView", query: { id: row.id } });
}

function handleLog(row: UserType) {
  router.push({ name: "UserLogView", query: { userId: row.id, userName: row.userName } });
}

function handleAdd() {
  router.push({ name: "StudentAddView" });
}

function handleDelete(row: UserType) {
  ElMessageBox.confirm(`确认删除【${row.realName || row.userName}】吗？`, "提示", {
    type: "warning",
  })
    .then(() => {
      UserAPI.deleteUser(row.id).then(() => {
        ElMessage.success("删除成功");
        if (tableData.value.length === 1 && params.value.pageIndex > 1) {
          params.value.pageIndex -= 1;
        }
        getList();
      });
    })
    .catch(() => {});
}

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.student {
  padding: 16px;
}
</style>
